<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="机型编号" prop="modeCode">
          <el-input v-model="formData.modeCode" placeholder="请输入机型编号" style="width: 195px;" size="small"/>
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="formData.customerId" placeholder="请选择客户" clearable filterable size="small">
            <el-option v-for="customer in customerList" :key="customer.id" :label="customer.customerName"
                       :value="customer.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="生产仓" prop="productionWarehouseId">
          <el-select v-model="formData.productionWarehouseId" placeholder="请选择所在生产仓" clearable filterable size="small">
            <el-option v-for="warehouse in productionWarehouseList" :key="warehouse.id" :label="warehouse.name"
                       :value="warehouse.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="三方仓" prop="tripartiteWarehouseId">
          <el-select v-model="formData.tripartiteWarehouseId" placeholder="请选择所在三方仓" clearable filterable size="small" @change="handleTripartiteWarehouseBlur">
            <el-option v-for="warehouse in tripartiteWarehouseList" :key="warehouse.id" :label="warehouse.name"
                       :value="warehouse.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="直发客户" prop="isDirect">
          <el-select v-model="formData.isDirect" placeholder="请选择是否直发" clearable size="small" disabled>
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.IS_DIRECT)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="落地检" prop="landingQc">
          <el-select v-model="formData.landingQc" placeholder="请选择是否落地检" clearable size="small">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.LANDING_QC)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户零件号" prop="partNumber">
          <el-input v-model="formData.partNumber" placeholder="请输入客户零件号" style="width: 195px;" size="small"/>
        </el-form-item>
        <el-form-item label="零件简号" prop="partNumberShort">
          <el-input v-model="formData.partNumberShort" placeholder="请输入零件简号" style="width: 195px;" size="small"/>
        </el-form-item>
        <el-form-item label="物料箱容量" prop="boxCapacityCount">
          <el-input v-model="formData.boxCapacityCount" placeholder="请输入物料箱容量" style="width: 195px;" size="small"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as MaterialModeApi from '@/api/hs/materialmode';
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import {getWarehouseSimpleList} from "@/api/hs/warehouse";
import {getCustomerSimpleList} from "@/api/hs/customer";

export default {
  name: "MaterialModeForm",
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    }
  },
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        modeCode: undefined,
        customerId: undefined,
        productionWarehouseId: undefined,
        tripartiteWarehouseId: undefined,
        landingQc: undefined,
        partNumber: undefined,
        partNumberShort: undefined,
        isDirect: 1,
        boxCapacityCount: undefined,
      },
      // 表单校验
      formRules: {
        modeCode: [{required: true, message: '机型编号不能为空', trigger: 'blur'}],
        customerId: [{required: true, message: '客户不能为空', trigger: 'blur'}],
        productionWarehouseId: [{required: true, message: '生产仓不能为空', trigger: 'blur'}],
        // tripartiteWarehouseId: [{required: true, message: '三方仓不能为空', trigger: 'blur'}],
        landingQc: [{required: true, message: '落地检不能为空', trigger: 'blur'}],
        partNumber: [{required: true, message: '客户零件号不能为空', trigger: 'blur'}],
        partNumberShort: [{required: true, message: '零件简号不能为空', trigger: 'blur'}],
        // isDirect: [{required: true, message: '直发客户不能为空', trigger: 'blur'}],
        boxCapacityCount: [{required: true, message: '物料箱容量不能为空', trigger: 'blur'}],
      },
      productionWarehouseList: [],
      tripartiteWarehouseList: [],
      customerList: [],
    };
  },
  created() {
    this.getProductionWarehouseList();
    this.getTripartiteWarehouseList();
    this.getCustomerList();
  },
  methods: {
    getDictDatas,
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await MaterialModeApi.getMaterialMode(id);
          this.formData = res.data;
          this.title = "修改机型信息";
        } finally {
          this.formLoading = false;
        }
      }
      this.title = "新增机型信息";
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await MaterialModeApi.updateMaterialMode(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await MaterialModeApi.createMaterialMode(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        modeCode: undefined,
        customerId: undefined,
        productionWarehouseId: undefined,
        tripartiteWarehouseId: undefined,
        landingQc: undefined,
        partNumber: undefined,
        partNumberShort: undefined,
        isDirect: 1,
        boxCapacityCount: undefined,
      };
      this.resetForm("formRef");
    },
    /** 查询仓库列表 */
    async getProductionWarehouseList() {
      let query = {
        warehouseType: 'PRODUCTION'
      }
      getWarehouseSimpleList(query).then(res => {
        this.productionWarehouseList = res.data;
      })
    },
    /** 查询仓库列表 */
    async getTripartiteWarehouseList() {
      let query = {
        warehouseType: 'TRIPARTITE'
      }
      getWarehouseSimpleList(query).then(res => {
        this.tripartiteWarehouseList = res.data;
      })
    },
    /** 查询客户列表 */
    async getCustomerList() {
      getCustomerSimpleList().then(res => {
        this.customerList = res.data;
      })
    },

    /** 处理三方仓失去焦点事件 */
    handleTripartiteWarehouseBlur() {
      // 如果三方仓不为空，则修改isDirect为0（直发）
      if (this.formData.tripartiteWarehouseId) {
        this.formData.isDirect = 0;
      } else {
        // 如果三方仓为空，则修改isDirect为1（非直发）
        this.formData.isDirect = 1;
      }
    }

    // /** 处理直发客户切换事件 */
    // handleIsDirectChange(value) {
    //   // 当切换直发客户选项时，清空三方仓的值
    //   this.formData.tripartiteWarehouseId = undefined;
    // }
  }
};
</script>
